package top.infopub.mgr.sg.web;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.sg.service.CoopInfoLogService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.sys.service.AreaService;
import top.infopub.mgr.sys.service.CityService;
import top.infopub.mgr.sys.service.LocationAreaDataService;
import top.infopub.mgr.sys.service.ProvinceService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.sg.CoopInfo;
import top.infopub.model.sg.CoopInfoLog;
import top.infopub.model.sys.Area;
import top.infopub.model.sys.City;
import top.infopub.model.sys.Province;

import com.github.pagehelper.Page;


/**
 * 合作单位信息
 * @author ZhangWenLiang
 * @version 2020年1月7日
 * @see CoopInfoController
 * @since
 */
@Controller
@RequestMapping("/coopinfo")
public class CoopInfoController extends GenericController {

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    private CityService cityService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private LocationAreaDataService locationAreaDataService;

    @Autowired
    private CoopInfoLogService coopInfoLogService;

    /**
     * 合作单位信息列表并加载省份下拉框
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        Set<Province> provinces = locationAreaDataService.selectProvincesAndsort();
        request.setAttribute("provinces", provinces);
        return "sg/lay-coopinfo-list";
    }

    /**
     * 根据省份查找城市
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/getCityByPro")
    @ResponseBody
    public Map<String, Object> getCityByPro(HttpServletRequest request,
                                            HttpServletResponse response) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String provinceCode = request.getParameter("provinceCode");
            Set<City> citys = locationAreaDataService.selectCitysByProvIdAndSort(provinceCode);
            map.put("citys", citys);
        }
        catch (Exception e) {
            log.error("根据省份查找城市异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据城市查找区县
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAreaByCity")
    @ResponseBody
    public Map<String, Object> getAreaByCity(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String cityCode = request.getParameter("cityCode");
            Set<Area> areas = locationAreaDataService.selectAreasByCityIdAndSort(cityCode);
            map.put("areas", areas);
        }
        catch (Exception e) {
            log.error("根据城市查找区县异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 新增单位
     * @param coopInfo
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/addCoop")
    public @ResponseBody RspVo<CoopInfo> addCoop(HttpServletRequest request, CoopInfo coopInfo) {
        // 新增
        if (StringUtils.isBlank(coopInfo.getId())) {
            //判断单位名称是否存在
            if (coopInfoService.selectByCoopName(coopInfo.getCoopName())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("单位【" + coopInfo.getCoopName()
                                                                + "】已经存在~");
            }
        }
        else {
            //判断单位名称是否存在
            if (coopInfoService.selectByCoopNameAndId(coopInfo.getCoopName(), coopInfo.getId())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("单位【" + coopInfo.getCoopName()
                                                                + "】已经存在~");
            }
        }
        String provinceCode = request.getParameter("provinceCode");
        String cityCode = request.getParameter("cityCode");
        String areaCode = request.getParameter("areaCode");
        coopInfo.setRefProvinceId(provinceCode);
        coopInfo.setRefCityId(cityCode);
        coopInfo.setRefAreaId(areaCode);
        String proName = locationAreaDataService.selectProvinceNameById(provinceCode);
        String cName = locationAreaDataService.selectCityNameById(cityCode);
        String areaName = "";
        if (StringUtils.isNotBlank(areaCode)) {
            areaName = locationAreaDataService.selectAreaNameById(areaCode);
        }
        String cityName = proName + cName + areaName;
        coopInfo.setCityName(cityName);
        coopInfoService.saveCoopInfo(coopInfo);
        if (StringUtils.isEmpty(coopInfo.getId())) {
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "新增单位 - 单位名称:"
                                                                + coopInfo.getCoopName().trim(),
                null);
        }
        return RspVo.getSuccessResponse(coopInfo);
    }

    /**
     * 检查输入的单位名是否被占用(新增时使用)
     * @param coopName 单位名
     * @return true 被占用, false 没有被占用
     */
    @RequestMapping(value = "/checkCoopNameIsExist")
    @ResponseBody
    public boolean checkCoopNameIsExist(String coopName) {
        if (StringUtils.isBlank(coopName)) {
            return false;
        }
        return coopInfoService.selectByCoopName(coopName);
    }

    /**
     * 修改单位
     * @param coopInfo
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/editCoop")
    public @ResponseBody RspVo<CoopInfo> editCoop(HttpServletRequest request, String id,
                                                  CoopInfo coopInfo) {
        // 修改
        //判断单位名称是否存在
        if (coopInfoService.selectByCoopNameAndId(coopInfo.getCoopName(), coopInfo.getId())) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("单位【" + coopInfo.getCoopName()
                                                            + "】已经存在~");
        }
        coopInfo.setId(id);
        String provinceCode = request.getParameter("refProvinceId");
        String cityCode = request.getParameter("refCityId");
        String areaCode = request.getParameter("refAreaId");
        coopInfo.setRefProvinceId(provinceCode);
        coopInfo.setRefCityId(cityCode);
        coopInfo.setRefAreaId(areaCode);
        String proName = locationAreaDataService.selectProvinceNameById(provinceCode);
        String cName = locationAreaDataService.selectCityNameById(cityCode);
        String areaName = "";
        if (StringUtils.isNotBlank(areaCode)) {
            areaName = locationAreaDataService.selectAreaNameById(areaCode);
        }
        String cityName = proName + cName + areaName;
        coopInfo.setCityName(cityName);
        coopInfoService.udpCoopInfo(coopInfo);
        if (StringUtils.isEmpty(coopInfo.getId())) {
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE,
                "修改单位 - 单位Id:" + coopInfo.getId(), null);
        }
        return RspVo.getSuccessResponse(coopInfo);
    }

    /**
     * 检查输入的单位名是否被占用(编辑时使用)
     * @param coopName 单位名
     * @param id 当前被修改的单位Id
     * @return true 被占用, false 没有被占用
     */
    @RequestMapping(value = "/checkNewCoopNameIsExist")
    @ResponseBody
    public boolean checkNewCoopNameIsExist(String coopName, String id) {
        if (StringUtils.isBlank(coopName)) {
            return false;
        }
        return coopInfoService.selectByCoopNameAndId(coopName, id);
    }

    /**
     * 根据id查询单位保存记录
     * @param id 单位Id
     * @return
     * @see
     */
    @RequestMapping("/selectById")
    @ResponseBody
    public RspVo<CoopInfoLog> selectById(String coopInfoId) {
        CoopInfoLog t = new CoopInfoLog();
        t.setCoopInfoId(coopInfoId);
        List<CoopInfoLog> logs = coopInfoLogService.selectByEntityWhere(t);
        return RspVo.getSuccessResponse(0, logs);
    }

    /**
     * 根据id查询单位详情
     * @param id 单位Id
     * @return
     * @see
     */
    @RequestMapping("/queryById")
    public @ResponseBody Map<String, Object> queryById(HttpServletRequest request) {
        boolean flag = true;
        String id = request.getParameter("id");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            CoopInfo coopInfo = coopInfoService.selectByPrimaryKey(id);
            map.put("coopInfo", coopInfo);
        }
        catch (Exception e) {
            log.error("根据合作单位查找保存记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 合作单位信息列表数据
     * @return
     */
    @RequestMapping("/queryCoopInfo")
    @ResponseBody
    public RspVo<CoopInfo> queryCoopInfo(CoopInfo coopInfo, ParamPage paramPage) {
        Page<CoopInfo> page = new Page<CoopInfo>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = coopInfoService.selectPageByDomainWhere(page, coopInfo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

}
